import AlertDialog from '@/components/AlertDialog';
import ListEmptyLoadingComponent from '@/components/ListEmptyLoadingComponent';
import WifiSignal from '@/components/Signal/WifiSignal';
import G4Signal from '@/components/Signal/4GSignal';
import { stationApi, StationInverter } from '@/services/api/stationApi';
import ArrayUtils from '@/utils/ArrayUtils';
import Slider from '@react-native-community/slider';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import React, {
  useCallback,
  useEffect,
  useRef,
  useState,
  useTransition,
} from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, View, Text, TouchableOpacity } from 'react-native';
import { Button, Icon, Switch, useAppTheme } from 'tsun-smart-ui';
import InverterEditBottomSheet from '@/components/InverterEditBottomSheet';
import { BottomSheetModal } from '@gorhom/bottom-sheet';
import NativeToast from '~/specs/NativeToast';

const InverterControlScreen: React.FC = () => {
  const { t } = useTranslation();
  const route = useRoute<RouteProp<any>>();
  const navigation = useNavigation();
  const [inverterList, setInverterList] = useState<StationInverter[]>([]);
  const [loading, startTransition] = useTransition();
  const appTheme = useAppTheme();
  const [editingInverter, setEditingInverter] = useState<StationInverter>();
  const bottomSheetRef = useRef<BottomSheetModal>(null);

  useEffect(() => {
    if (ArrayUtils.isEmpty(inverterList)) {
      onReload();
    }
  }, []);

  const onReload = useCallback(() => {
    startTransition(() => {
      if (route.params?.stationId) {
        stationApi
          .getStationInverterSettings(route.params?.stationId)
          .then((res) => {
            setInverterList(res.data);
          });
      }
    });
  }, [route.params?.stationId]);

  const updateInverter = useCallback(
    (inverter: Partial<StationInverter>) => {
      NativeToast.makeToastActivity();
      stationApi
        .updateStationInverter(inverter)
        .then((newInverter) => {
          NativeToast.hideToastActivity();
          const index = inverterList.findIndex(
            (item) => item.deviceSn === inverter.deviceSn
          );
          if (index === -1) {
            onReload();
            return;
          }
          let newInverterList = [...inverterList];
          newInverterList[index] = newInverter.data;
          setInverterList(newInverterList);
        })
        .catch((reason) => {
          NativeToast.hideToastActivity();
        });
    },
    [inverterList, onReload]
  );

  const renderItem = useCallback(
    ({ item }: { item: StationInverter; index: number }) => {
      const isOn = item.shutdown === 0;
      const isDeviceOffline = item.deviceStatus === 'offline';
      let signal = item.singleStrength ?? 0;
      if (isDeviceOffline) {
        signal = 0;
      }
      return (
        <View className="px-3 py-4 rounded-lg bg-fill2 mb-2 items-stretch">
          <View className="flex-row">
            <Text className="text-[16px] font-medium text-text1">
              {item.deviceName}
              {'  '}
              <G4Signal signal={signal} />
            </Text>
            <View className="flex-1" />
            <Switch
              disabled={isDeviceOffline}
              value={isOn}
              onValueChange={(value) => {
                const shutdownValue = value ? 0 : 1;
                updateInverter({
                  shutdown: shutdownValue,
                  deviceSn: item.deviceSn,
                });
              }}
            />
          </View>
          <Text className="text-[14px] text-text3">SN: {item.deviceSn}</Text>
          <View className="bg-line1 h-[1px] my-3" />
          <TouchableOpacity
            className="flex-row items-center"
            disabled={isDeviceOffline}
            hitSlop={{
              top: 10,
              bottom: 10,
            }}
            onPress={() => {
              setEditingInverter(item);
              console.log(bottomSheetRef.current);
              bottomSheetRef.current?.present();
            }}
          >
            <Text className="text-text2 text-[14px]">
              {t('user.power_regulation', { defaultValue: '功率调节' })}
            </Text>
            <View className="flex-1" />
            <Text className="text-[16px] font-medium text-text1">
              {item.ratePowerReal ?? '--'}W
            </Text>
            {!isDeviceOffline && (
              <Icon
                name="right"
                color={appTheme.colors?.neutral?.primary}
                size={12}
                style={{marginLeft: 8}}
              />
            )}
          </TouchableOpacity>
        </View>
      );
    },
    [appTheme, t, updateInverter]
  );

  return (
    <>
      <View className="flex-1">
        <FlatList
          className="flex-1"
          contentContainerClassName="px-3 py-3"
          data={inverterList}
          renderItem={renderItem}
          refreshing={loading}
          onRefresh={onReload}
          ListEmptyComponent={ListEmptyLoadingComponent}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
      <InverterEditBottomSheet
        ref={bottomSheetRef}
        inverter={editingInverter}
        onUpdate={updateInverter}
      />
    </>
  );
};

export default InverterControlScreen;
